<?php

namespace App\Listeners\OpenShop;

use App\Enums\OpenShop\Notify\SystemNotifyCacheCode;
use App\Events\OpenShop\SystemNotifyCenterEvent;
use App\Listeners\BaseListener;
use App\Models\System\SystemNotifyCenterModel;
use App\Models\System\SystemNotifyUserModel;
use App\Service\System\SystemNotifyService;
use Illuminate\Support\Facades\Redis;

class SystemNotifyAppListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Handle the event.
     *
     * @return void
     */
    public function handle(SystemNotifyCenterEvent $event)
    {
        $notifyModel = $event->notifyCenterModel;

        if (empty($notifyModel->summary)) {
            return;
        }

        if (!empty($event->prePushTargetList)) {
            $preTargetList = $event->prePushTargetList;
            foreach ($preTargetList as $value) {
                $userList[] = [
                    'id' => $value
                ];
            }
        } else {
            $userList = SystemNotifyService::getTargetUserList($notifyModel);
        }

        if (empty($event->prePushTargetList)) {
            $notifyModel->status = SystemNotifyCenterModel::NOTIFY_STATUS_2;
            $notifyModel->save();
        }

        Redis::pipeline(function ($pipe) use ($userList, $notifyModel) {
            foreach ($userList as $user) {
                // 用户-分类消息列表
                $key = SystemNotifyCacheCode::getUserNotifyListKey($user['id'], $notifyModel->type);
                $pipe->LPush($key, $notifyModel->id);

                // 用户-所有消息
                $allUnreadListKey = SystemNotifyCacheCode::getUserNotifyListKey($user['id'], 0);
                $pipe->LPush($allUnreadListKey, $notifyModel->id);

                // 用户-未读消息列表
                $unreadNumKey = SystemNotifyCacheCode::getUserUnreadListKey($user['id'], $notifyModel->type);
                $pipe->LPush($unreadNumKey, $notifyModel->id);

                // 用户-弹窗数据列表
                if ($notifyModel->isPopup) {
                    $popKey = SystemNotifyCacheCode::getUserNotifyPopListKey($user['id']);
                    $pipe->LPush($popKey, $notifyModel->id);
                }
            }
        });

        collect($userList)->chunk(500)->each(function ($value) use ($notifyModel) {
            $insertData = [];
            foreach ($value as $item) {
                $insertData[] = [
                    'notifyCenterId'   => $notifyModel->id,
                    'notifyCenterType' => $notifyModel->type,
                    'userId'           => $item['id'],
                    'readAt'           => 0,
                    'createdAt'        => time()
                ];
            }
            SystemNotifyUserModel::query()->insert($insertData);
        });


        if (empty($event->prePushTargetList)) {
            SystemNotifyService::recordLog($notifyModel, '应用内 消息推送成功');
        } else {
            SystemNotifyService::recordLog($notifyModel, '应用内 消息预推送成功');
        }

        // 删除 30 天 未读 消息
        SystemNotifyUserModel::query()
                             ->where('readAt', 0)
                             ->where('createdAt', '<', time() - (30 * 86400))
                             ->delete();
    }
}
